package com.hrbxlh.interceptor;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.hrbxlh.dao.MemberDao;
import com.hrbxlh.dao.RoleDao;
import com.hrbxlh.util.ConfigFileUtil;
import com.hrbxlh.util.SessionValues;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* -------------------------------------------------------
* Copyright (c) 2017, 鑫联华信息科技股份有限公司
* All rights reserved.
* FileName：CommonInterceptor.java
* Description：用于拦截登陆的action，如果没登陆，跳转到登陆页面，
* History：
* Date           Author               Desc
* 2017.4.21		  xzx                 建立
* -------------------------------------------------------
*/
public class CommonInterceptor extends HandlerInterceptorAdapter{
    
	private final Logger log = Logger.getLogger(CommonInterceptor.class.getName());  
    public static final String LAST_PAGE = "beforeLogin";

    @Resource(name="memberDao")
    private MemberDao memberDao;

    @Resource(name="roleDao")
    private RoleDao roleDao;

    /**  
     * @description 在业务处理器处理请求之前被调用  
     * 				如果返回false  
     *     			从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链 
     * 				如果返回true  
     *    			执行下一个拦截器,直到所有的拦截器都执行完毕  
     *    			再执行被拦截的Controller  
     *    			然后进入拦截器链,  
     *    			从最后一个拦截器往回执行所有的postHandle()  
     *    			接着再从最后一个拦截器往回执行所有的afterCompletion()  
     */    
    @Override
    public boolean preHandle(HttpServletRequest request,    
            HttpServletResponse response, Object handler) throws Exception {    

        String urlString = request.getRequestURI();
        Object msg = request.getSession().getAttribute("userMsg");
        log.info("--------------url为："+urlString);
        if(msg == null){
            log.info("未登录拦截跳转首页，url为："+urlString);
            //post直接返回失败信息
            String type = request.getHeader("X-Requested-With");
            if(type != null && type.equals("XMLHttpRequest")){
                String data="";
                Map<String, Object> map = new HashMap<String, Object>();
                if(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString().startsWith("/server") || request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString().startsWith("/template") || request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString().startsWith("/lab")){
                    response.setContentType("application/json;charset=UTF-8");
                    PrintWriter write = response.getWriter();
                    data = "{\"code\":401,\"message\":\"登录过期，请重新登录\"}";
                    write.println(data);
                    write.flush();
                }else{
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter write = response.getWriter();
                    data = "{\"logTimeOut\":\"error\",\"result\":\"error\",\"resultMark\":\"error\",\"finalflag\":\"error\",\"resultFlag\":false,\"flag\":false,\"failMsg\":\"登录过期，请重新登录\",\"message\":\"登录过期，请重新登录\",\"msg\":\"登录过期，请重新登录\",\"errMsg\":\"登录过期，请重新登录\",\"resultMsg\":\"登录过期，请重新登录\",\"errorMsg\":\"登录过期，请重新登录\"}";
                    write.println(data);
                    write.flush();
                }
                return false;
            }

            String[] keysArray = {"project_name"};
            Map<String, Object> pathMap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
            if(urlString.endsWith("/") || urlString.endsWith(pathMap.get("project_name").toString())){
                return true;
            }
            response.sendRedirect(request.getContextPath());
            return false;
        }else{
            Map<String, Object> map = new SessionValues().getSessionValues(new String[]{"stuorteaId"}, request, "userMsg");
            map = memberDao.getMemberMsgById(map);
            if(map == null){
                request.getSession().removeAttribute("userMsg");
                response.sendRedirect("");
                return false;
            }
            map.put("menuHref",  request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE));
            //此处按照存的角色id以及他的得到的url去数据库查询此人是否有这个权限，
            List<Map<String, Object>> list = roleDao.getPermissionByRoleId(map);
            if(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).equals("/")){
                response.sendRedirect("skipMain");
            }
            if(list != null && list.size() != 0){
                return true;
            }
            if(request.getMethod().equals("GET")){
                response.sendRedirect("/noPermission");
            }else {
                request.getRequestDispatcher("/noPermissionPost").forward(request, response);
            }
            return false;
        }

//    return true;
    }    
    
    /** 
     * @description 在业务处理器处理请求执行完成后,生成视图之前执行的动作    
     * 				可在modelAndView中加入数据，比如当前时间 
     */  
    @Override    
    public void postHandle(HttpServletRequest request,    
            HttpServletResponse response, Object handler,    
            ModelAndView modelAndView) throws Exception {     
       
    }    
    
    /**  
     * @description 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等   
     *				当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()  
     */    
    @Override    
    public void afterCompletion(HttpServletRequest request,    
            HttpServletResponse response, Object handler, Exception ex)    
            throws Exception {        
    }    
  
}    